using System;
using System.Diagnostics;
using System.IO;
using System.Security.Policy;
using System.Xml.XPath;
//for evidence object

namespace SharpService.Installer
{
    public class Program
    {
        // The main entry point for the process
        private static void Main(string[] args)
        {
            string dir = "";
            try
            {
                FileInfo configFile = new FileInfo(args[0]);
                if (!configFile.Exists)
                {
                    Log.Write(EventLogEntryType.Error, "Unable to find config: " + args[0]);
                    return;
                }
                XPathDocument doc = new XPathDocument(args[0]);
                XPathNavigator nav = doc.CreateNavigator();
                XPathNodeIterator services = nav.Select("//service");
                dir = nav.SelectSingleNode("//dir").Value;
                if (dir != null)
                {
                    System.IO.Directory.SetCurrentDirectory(dir);
                }
                // Create application domain setup information
                AppDomainSetup domaininfo = new AppDomainSetup();
                domaininfo.ApplicationBase = dir;
                domaininfo.PrivateBinPath = null;
                domaininfo.PrivateBinPathProbe = null;
                //Create evidence for the new appdomain from evidence of the current application domain
                Evidence adevidence = AppDomain.CurrentDomain.Evidence;
                // Create appdomain
                AppDomain domain = AppDomain.CreateDomain("SharpServiceDomain", adevidence, domaininfo);
                string containerPath = AppDomain.CurrentDomain.BaseDirectory + "SharpService.Container.exe";
                int result = domain.ExecuteAssembly(containerPath, null, args);
                if (result != 0)
                {
                    Log.Write(EventLogEntryType.Error,
                              "Failed to start container: " + containerPath + " with config: " + args[0]);
                }
                else
                {
                    Log.Write(EventLogEntryType.Information, "Started: " + args[0]);
                }
            }
            catch (Exception failed)
            {
                string dirs = "Root Dir: " + AppDomain.CurrentDomain.BaseDirectory;
                dirs += " Service Dir: " + dir;
                Log.Write(EventLogEntryType.Error, failed.Message, failed.StackTrace);
                Log.Write(EventLogEntryType.Error, "Check directories for config and libs - " + dirs);
            }
        }
    }
}